package com.gee.spring.boot.oauth2.auth.config.web;

import com.gee.spring.boot.oauth2.common.util.http.ResponseUtil;
import com.gee.spring.boot.oauth2.common.util.result.ResultCode;
import com.gee.spring.boot.oauth2.common.util.result.ResultUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * desc:
 *
 * @author gee
 * @date 2020/04/01 22:32
 */
@Component(value = "authenticationFailureHandler")
public class GeeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (e instanceof BadCredentialsException){
            ResponseUtil.writeJson(response, ResultUtil.error(ResultCode.ERROR_USERNAME_PASSWORD));
        }else  if (e instanceof LockedException){
            ResponseUtil.writeJson(response, ResultUtil.error(ResultCode.USER_LOCKED));
        }else  if (e instanceof AccountExpiredException){
            ResponseUtil.writeJson(response, ResultUtil.error(ResultCode.USER_EXPIRED));
        }else  if (e instanceof DisabledException){
            ResponseUtil.writeJson(response, ResultUtil.error(ResultCode.USER_DISABLED));
        }else  if (e instanceof InternalAuthenticationServiceException){
            ResponseUtil.writeJson(response, ResultUtil.error(ResultCode.ERROR_USERNAME_PASSWORD));
        }
    }
}
